﻿using System;
using System.Collections.Generic;
using System.Text;

namespace MICZ.CodeBuilder.Commons.DynamicExtensions
{
    public class DynamicObjectHelper : System.Dynamic.DynamicObject
    {
        //public PluginsDynamic()
        //{
        //    map = new Dictionary<string, object>();
        //}
        public override IEnumerable<string> GetDynamicMemberNames()
        {
            // return base.GetDynamicMemberNames();
            return map.Keys;
        }

        public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
        {
            if (map != null)
            {
                string name = binder.Name;
                object value;
                if (map.TryGetValue(name, out value))
                {
                    result = value;
                    return true;
                }
            }
            return base.TryGetMember(binder, out result);
        }

        System.Collections.Generic.Dictionary<string, object> map;

        public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result)
        {
            if (binder.Name == "set" && binder.CallInfo.ArgumentCount == 2)
            {
                string name = args[0] as string;
                if (name == null)
                {
                    result = null;
                    return false;
                }
                if (map == null)
                {
                    map = new System.Collections.Generic.Dictionary<string, object>();
                }
                object value = args[1];
                if (map.ContainsKey(name))
                {
                    map.Remove(name);
                }
                map.Add(name, value);
                result = value;
                return true;
            }
            return base.TryInvokeMember(binder, args, out result);
        }
        public int GetMemberCount()
        {
            if (map != null)
            {
                return map.Count;
            }
            return 0;
        }
    }
}
